import Vue from 'vue'
import axios from 'axios'
import router from '../router'
import JSBridge from './JSBridge'
import {
  Toast
} from 'vant'

Vue.prototype.buildNo = 0
axios.defaults.timeout = 5000
axios.defaults.baseURL = process.env.HOST
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

let loadingInstance = null
const jsBridge = JSBridge.getInstance()

axios.interceptors.request.use(config => {
  if (config.headers.hasOwnProperty('openAuth')) {
    return config
  }
  if (!config.headers.hasOwnProperty('FastMode')) {
    loadingInstance = Toast.loading({
      mask: true,
      duration: 0,
      position: 'middle',
      className: 'toast-loading',
      forbidClick: true
    })
    console.log('Loading Mode request')
  }
  return new Promise((resolve, reject) => {
    jsBridge.getAccessToken((token) => {
      config.headers.Authorization = 'Bearer ' + token
      return resolve(config)
    })
  })
  // return retry
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(response => {
  loadingInstance !== null && loadingInstance.clear()
  // Do something with response data
  if (process.env.NODE_ENV === 'development') {
    console.log(response.data)
  }
  if (response.headers.hasOwnProperty('build')) {
    Vue.prototype.buildNo = response.headers.build
  }
  return response.data
}, error => {
  loadingInstance !== null && loadingInstance.clear()
  // Do something with response error
  if (typeof error === 'object' && error.response) {
    if (process.env.NODE_ENV === 'development') {
      console.log(error.response)
    }
    if (error.response.status === 401) {
      Toast(error.response.data.message)
    } else if (error.response.status === 402 || error.response.status === 403) {
      Toast('需要您登录')
      jsBridge.goToLoginPage(null, () => {})
    } else if (error.response.status === 429) {
      Toast('您刷新太频繁了，系统有点受不了')
    } else {
      if (error.response.data) {
        Toast(error.response.data.message)
      } else {
        router.replace({
          name: 'error',
          params: error
        })
        // Toast('网络请求超时或者页面内部错误')
      }
    }
  } else {
    router.replace({
      name: 'error',
      params: error
    })
  }
  return Promise.reject(error.response)
})

export default axios
